using System;
using System.Collections.Generic;
using Microsoft.Practices.ObjectBuilder2;

namespace Common.Unity.Extensions.PropertyMapper
{
	class CollectionPropertyExpressionMapping : PropertyExpressionMapping
	{
		readonly NamedTypeBuildKey firstItemKey;
		readonly NamedTypeBuildKey secondItemKey;

		public CollectionPropertyExpressionMapping( string firstExpression, string secondExpression )
			: base( firstExpression, secondExpression )
		{}

		public CollectionPropertyExpressionMapping( string firstExpression, string secondExpression, NamedTypeBuildKey firstItemKey, NamedTypeBuildKey secondItemKey )
			: this( firstExpression, secondExpression, firstItemKey, secondItemKey, null )
		{}

		public CollectionPropertyExpressionMapping( string firstExpression, string secondExpression, NamedTypeBuildKey firstItemKey, NamedTypeBuildKey secondItemKey, Type typeConverterType ) : base( firstExpression, secondExpression, typeConverterType )
		{
			this.firstItemKey = firstItemKey;
			this.secondItemKey = secondItemKey;
		}

		public override IPropertySetterInfo CreateProperty( PropertyMappingContext context )
		{
			LinkedList<PropertyMappingExpressionContext> 
				sourceContext = PropertyMappingExpressionContextResolver.Eval( context.Source, FirstExpression ),
				targetContext = PropertyMappingExpressionContextResolver.Eval( context.Target, SecondExpression );
			return new CollectionPropertyMappingExpressionPropertySetterInfo( sourceContext.Last.Value, targetContext.Last.Value, SecondItemKey );
		}

		public override PropertyExpressionMapping CreateMirror()
		{
			PropertyExpressionMapping result = new CollectionPropertyExpressionMapping( SecondExpression, FirstExpression, secondItemKey, firstItemKey );
			return result;
		}

		public NamedTypeBuildKey FirstItemKey
		{
			get { return firstItemKey; }
		}

		public NamedTypeBuildKey SecondItemKey
		{
			get { return secondItemKey; }
		}
	}
}